/**
 * https://leetcode.cn/problems/island-perimeter/
 * @param grid m * n 个小网格
 * @returns 小网格组成的周长
 */
function islandPerimeter(grid: number[][]): number {
  let total = 0;
  const rowLength = grid.length;
  const colLength = grid[0].length;

  for (let row = 0; row < rowLength; row++) {
    for (let col = 0; col < colLength; col++) {
      const value = grid[row][col];
      if (value === 0) continue;
      total += 4;

      // 每一个格子只需要考虑下面和右边就好了
      if (row < rowLength - 1 && grid[row + 1][col]) {
        total -= 2;
      }

      if (col < colLength - 1 && grid[row][col + 1]) {
        total -= 2;
      }
    }
  }

  return total;
}
